#!/bin/sh
#
# Copyright (c) 2007-2009 The PureDarwin Project.
# All rights reserved.
#
# @LICENSE_HEADER_START@
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# @LICENSE_HEADER_END@
#

#
# Copyright (c) 2005, Apple Computer, Inc. All rights reserved.
#
# @APPLE_BSD_LICENSE_HEADER_START@
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1.  Redistributions of source code must retain the above copyright
#     notice, this list of conditions and the following disclaimer.
# 2.  Redistributions in binary form must reproduce the above copyright
#     notice, this list of conditions and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
# 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
#     its contributors may be used to endorse or promote products derived
#     from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# @APPLE_BSD_LICENSE_HEADER_END@
#

#
# probono <probono@puredarwin.org>
# aladin   <aladin@puredarwin.org>
#

#
# Set up a basic PureDarwin system
#
# WARNING: this will destroy all data on the target!
#
# Based on darwinmaster.sh by
#       Kevin Van Vechten <kvv@apple.com>
# Based on buildcd.sh by
#       Shantonu Sen      <ssen@opendarwin.org>
#       Felix Kronlage    <fkr@opendarwin.org>
#       Chuck Remes       <cremes@opendarwin.org>
#

#
# Changelog
#
# 20090313 - See hg log (mercurial) and/or svn log from now - aladin
# 20090310 - Enabled PureFoundation 
#            pseudo network support - aladin
# 20090208 - Enabled xnu-dev (voodoo Release 1.0 Rev A)
#            Developer choice, minor fixes - aladin
# 20081225 - Enabled xnu-dev (voodoo Release 1.0 Rev 1)
#            Minor fixes about bootloader
#            Provide startupfiletool, more WMs - aladin
# 20081224 - PureDarwin Xmas released!
# 20081219 - Added dtrace, keymaps (for X) in pd_roots
#            Autoload X via launchd, minor fixes - aladin
# 20081217 - Assimilated pd_makeiso setup script
#            Add qemu-img and mkisofs binary tool
#            Fixed guestOS in .vmx, minor fixes - aladin 
# 20081212 - Fixed mount manually to $MOUNT - probono
# 20081212 - Added zfs to pd_roots - fixed missingstuff - aladin 
# 20081211 - We can't use missingstuff any more, need solve it
#            Use entire disk, not just 256 MB - probono
# 20081210 - Mount manually to $MOUNT - probono
# 20081210 - Fixed experimental packages built with 9F33pd1.plist
#            "nano" release uses launchd too, cosmetic updates - aladin
# 20081209 - License header update, minor updates
#            Assimilated "nano" setup script 
#            Added autozone to pd_roots - aladin
# 20081030 - Add patched CF, IOKitUser, objc4 and launchd
#            Added pam to pd_roots (for login & co) - aladin
# 20081022 - Fixed diskarbitrationd nag popup - probono
# 20081002 - Cleaned again - aladin
# 20080927 - Added .vmwarevm extension detection and support
#            Minor fixes - aladin 
# 20080926 - Many updates, umount fixed, vmware drivers cleaned 
#            Merge of pd_setup and pd_makedmg - aladin
# 20080925 - Fixed shell interactive mode in "nano"
#            Minor updates, saving more spaces - aladin 
# 20080921 - Added .zshrc, removed single user mode
#            Added grep in pd_roots - aladin
# 20080917 - Minor updates and fixes 
#            Added zsh interactive mode (for "nano"), system_cmds (ps), 
#            file_cmds (ls), diskdev_cmds (devfs), adv_cmds (ps),
#            libutil (mount), text_cmds (cat), in pd_roots - aladin
# 20080831 - Minor updates and fixes
#            Added BootCache in pd_roots - aladin
# 20080827 - Less missingstuf: PCSC.framework (replaced by pcsc-lite)
#            Added (temporary) VMware-Drivers-OpenSource.zip
#            Minor updates - aladin
# 20080818 - Fixed minor errors
#            Added vim in pd_roots
#            Fake VMware guest OS detection
#            Added pd_injectuser in pd_contrib/
#            Added multi-user support - aladin
# 20080806 - Added timezone support
#            Fixed errors found with debug activated (/var/log/syslog)
#            Fixed pd_binaryroots (forgot to add ipsec in the previous commit)
#            Fixed (almost) hostname - aladin
# 20080803 - Updating booter from v5.0.132_dfe_r28 to v5.0.132_dfe_r146
#            Added IOBDStorageFamily in pd_drivers
#            Changed missingstuff to override target existence test
#            Less missingstuff: com.apple.securityd.plist, securityd,
#                               libsecurity, Security.framework (9D34),
#                               libipsec (9E17), libcrypto (openssl), ...  
#            Launchd debug and verbose boot log via syslog
#            DTrace support
#            motd and hostname are back! - aladin
# 20080527 - Fixed minor bugs - aladin
# 20080525 - Fork for "nano" - probono
# 20080523 - Using BinaryDrivers from DarwinBuild - probono
# 20080522 - Changed missingstuff not to use "L" since that
#            filled up the disk too quickly and removed
#            some of the missingstuff that is now available - probono
# 20080303 - Minor updates - aladin
# 20080108 - Initial version - probono
#

echo
echo "Set up a bootable PureDarwin system."
echo

################################################################################
# USAGE AND PREVENTIVE TESTS 
################################################################################

# Fail on return error code 
#set -e

# Fail on uninitialised variables
#set -u 

# Ensure root exclusivity
if [ "$UID" -ne 0 ]
then
	echo "You must be root in order to use $(basename $0)"
	exit 1
fi

# Usage statement
if [ $# -lt 2 ]; then
	echo "Usage: $(basename $0) available_output VolumeName"
	echo
	echo "       * Create a physical volume"
	echo "       $(basename $0) /Volumes/PureDarwin PureDarwin"
	echo "       $(basename $0) /dev/diskX PureDarwin"
	echo
	echo "       * Create an ISO 9660 image (.iso)"
	echo "       $(basename $0) /tmp/puredarwin.iso PureDarwin"
        echo
	echo "       * Create a ready-to-run VMware virtual machine (.vmwarevm)"
	echo "       $(basename $0) puredarwin.vmwarevm PureDarwin"
        echo
	echo "       * Create a ready-to-run VMware virtual disk (.vmdk)"
	echo "       $(basename $0) puredarwin.vmdk PureDarwin"
	echo
	exit 1
fi

# Ensure "" is not used as "target"
if [ "$1" = "" ]
then
	echo "$(basename $0): Empty output filename"
	exit 1
fi

# Ensure / is not used as "target"
if [ "$1" = "/" ]
then
	echo "Bad volume name: $1"
	exit 1
fi

# Ensure "target" exists (for real hw)
#if [ ! -e "$1" ]
#then
#	echo "Unknown volume name: $1"
#	exit 1
#fi

################################################################################
# PATHS AND VARIABLES
################################################################################

# Find out where this script lives
DIRNAME=$(cd $(dirname $0) && pwd)

# Reading global variables in pd_config file
source "$DIRNAME"/pd_config

# Destination output filename (aka "target")
TARGET="$1"

# FIXME remove redundancies btw TARGET and MOUNT
# Temporary pseudo PureDarwin Volume
MOUNT="/Volumes/$2" 

# Volume label of the target image (ie: PureDarwin)
VOLNAME="$2"

# Thinned binary roots and drivers root folder
PACKAGES=$DIRNAME/$DESTDIR

# Add PureDarwin binaries and scripts to $PATH
export PATH=$DIRNAME/pd_setup_files/:$PATH

# Location for temporary auxiliary ISO
ELTORITOISO=/tmp/eltorito.iso

# mkisofs binary path (note: it doesn't come from darwin nor macosx)
MKISOFS_BIN="$DIRNAME/pd_setup_files/mkisofs"

# qemu-img binary path (note: it doesn't come from darwin nor macosx)
QEMUIMG_BIN="$DIRNAME/pd_setup_files/qemu-img"

# Target detection (real disk or image/vm) via extension
EXT=`/usr/bin/basename $1 | awk -F "." '{print $2}'`

# Needed for Mr proper in trap() function
export DEVICE=""

###############################################################################
# INFORMATION
###############################################################################

echo "Darwin release: $DARWIN_RELEASE"
echo "Architecture  : $ARCH"
echo "Puredarwin    : $PUREDARWIN_RELEASE"
echo 
echo "\$1 (target) : $1"
echo "\$2 (name)   : $2"
echo

###############################################################################
# WARNINGS 
###############################################################################

echo "WARNING! this will destroy all data on $1"
printf "Continue? y[n] "
read CONT
if [ ! "$CONT" = "y" ]; then 
	exit 1
fi

echo "WARNING! Are you sure?"
printf "Continue? y[n] "
read CONT
if [ ! "$CONT" = "y" ]; then
	exit 1
fi

# Ensure "target" does not exist
if [ -e "$1" ]
then
	echo "WARNING! \`$1' is going to be rewritten"
	printf "Continue? y[n] "
	read CONT
	if [ ! "$CONT" = "y" ]; then
		echo "Aborting! \`$CONT' is not \`y'."
		exit 1
	fi
fi

echo
echo "OK, You have been warned.."
echo 

###############################################################################
# TRAP FUNCTIONS 
###############################################################################

function mr_proper {
	# Clean up temporary files and folders
	echo "Cleaning up"

	if [ -e $ELTORITOISO ];then
		echo "Removing $ELTORITOISO"
		rm $ELTORITOISO
	fi

	if [ -e /tmp/i386 ];then
		echo "Removing /tmp/i386"
		rm -r /tmp/i386
	fi

	CONT=""
	T_ERROR=""

	# Unmounting $MOUNT
	echo "WARNING! \`$MOUNT is going to be unmounted"
	printf "Continue? [y]n "
	read CONT
	if [ ! "$CONT" = "n" ]; then
		T_ERROR=`umount -f "$MOUNT" 2>&1`
		if [ $? -eq 0 ]; then
			echo "$MOUNT unmounted"
		else
			echo "umount failed (error: $T_ERROR)"
		fi
	fi	

	# Ejecting $DEVICE
	echo "WARNING! \`$DEVICE is going to be ejected"
	printf "Continue? [y]n "
	read CONT
	if [ ! "$CONT" = "n" ]; then
		T_ERROR=`hdiutil eject "$DEVICE" 2>&1`
		if [ $? -eq 0 ]; then
			echo "$DEVICE ejected"
		else
			echo "eject failed (error: $T_ERROR)"
		fi
	fi

	# Removing $MOUNT
	echo "WARNING! \`$MOUNT is going to be removed"
	printf "Continue? [y]n "
	read CONT
	if [ ! "$CONT" = "n" ]; then
		T_ERROR=`rmdir $MOUNT 2>&1`
		if [ $? -eq 0 ]; then
			echo "$MOUNT removed"
		else
			echo "rmdir failed: (error: $T_ERROR)"
		fi
	fi

	# diskarbitrationd is not present nor needed in the "nano" and "bootstrap" releases.
	if [ -e "/System/Library/LaunchDaemons/com.apple.diskarbitrationd.plist" ]; then
		# Revert diskarbitrationd mode to on 
		launchctl load /System/Library/LaunchDaemons/com.apple.diskarbitrationd.plist
	fi

	# Remove any previous copies
	#if [ -e $TARGET ];then
	#	rm -rf "$TARGET"
	#	echo " * $TARGET removed"
	#fi
}

# ^c (control-c) trapped
function trap_handler {
	echo 
	echo "Trap function."
	echo

	# iso, vmwarevm, vmdk, dmg, etc..
	if [ ! $EXT = "" ]; then
		mr_proper
	fi

	# Resetting trap
	trap - INT TERM EXIT

	exit 0 
}

# Trap ^c (control-c)
trap trap_handler INT TERM EXIT

###############################################################################
# BOOTLOADER PATH 
###############################################################################

# Default bootloader: DFE bootloader v5.0.132_dfe_r146 based on Apple boot-132
BOOTi386=$DIRNAME/pd_setup_files/boot/i386/

# Add Chameleon bootloader (default: yes)
if [ ! "$ADD_CHAMELEON" = "n" ]; then
	# The Chameleon bootloader 
	# (Apple Public Source License)
	# http://chameleon.osx86.hu
	#       Chameleon 2.0-RC1-r431-bin
	#       Chameleon 2.0-RC2-r640-bin
	#	Chameleon 2.0-RC3-r658-bin
	#	Chameleon-2.0-RC4-r684-bin

	T_CHAMELEON_RELEASE=""
	if [ "$ADD_CHAMELEON_RC1" = "y" ]; then
		T_CHAMELEON_RELEASE="Chameleon-2.0-RC1-r431-bin"
	fi
	
	if [ "$ADD_CHAMELEON_RC2" = "y" ]; then
		T_CHAMELEON_RELEASE="Chameleon-2.0-RC2-r640-bin"
	fi

	if [ "$ADD_CHAMELEON_RC3" = "y" ]; then
		T_CHAMELEON_RELEASE="Chameleon-2.0-RC3-r658-bin"
	fi

	if [ "$ADD_CHAMELEON_RC4" = "y" ]; then
		T_CHAMELEON_RELEASE="Chameleon-2.0-RC4-r684-bin"
	fi
	echo "Extracting Chameleon bootloader ($T_CHAMELEON_RELEASE)"
	# bsdtar 2.6.2 - libarchive 2.6.2 / Not in darwinbuild but present by default in Mac OS X
	#bsdtar xjf $PACKAGES/$T_CHAMELEON_RELEASE.root.tar.bz2 -C "$DIRNAME/pd_setup_files/" --include "*/i386"
	# tar (GNU tar) 1.15.1 / Present in darwinbuild and in Mac OS X
	gnutar xjf $PACKAGES/$T_CHAMELEON_RELEASE.root.tar.bz2 -C "$DIRNAME/pd_setup_files/" --wildcards '*/i386*'

	BOOTi386=$DIRNAME/pd_setup_files/$T_CHAMELEON_RELEASE/i386/
fi

BOOT0="boot0"   # MBR
BOOT1H="boot1h" # Stage 1 bootsector of EFI partition 
BOOT="boot"	# Stage 2 boot2 HFS+ startup file
CDBOOT="cdboot" # CD-ROM, etc..

###############################################################################
# PARTITIONING THE DISK 
###############################################################################

# iso, vmwarevm, vmdk, dmg, etc..
if [ ! $EXT = "" ]; then

	#
	# Ingredients for iso, dmg, vmwarevm, etc.. 
	#

	# Copy bootloader cdboot (but not only) for CD-ROMs
	echo "Populating /tmp/i386 with bootloader files"
	#echo "Making an ISO containing the boot-132 files and that has cdboot as its El Torito boot image at $ELTORITOISO..."
	mkdir -p /tmp/i386
	cp $BOOTi386/* /tmp/i386/

	cd /tmp/i386

		if [ ! -e $CDBOOT ]; then
			# if it's not there, we should exit
			echo "Aborting! cdboot cannot be found and is mandatory."
			mr_proper
			exit 1
		fi

		# mkisofs 
		#
		#       -quiet          Less verbose
		#       -V              Volume ID to be written into the master block
		#       -no-emul-boot   The boot image used to create "El Torito" bootable CDs is a 'no emulation' image
		#       -boot-load-size Specifies the number of "virtual" (512-byte) sectors to load in no-emulation mode.
		#                               The default is to load the entire boot file (here it is "4").
		#                               Some BIOSes may have problems if this is not
		#       -c              Path and filename of the boot catalog to be used when making an "El Torito" bootable CD
		#       -b              Eltorito_boot path and filename of the boot image to be used when making an "El Torito" bootable CD
		#       -o              Target written image file
		echo "Creating $ELTORITOISO"
		"$MKISOFS_BIN" -quiet -V "$VOLNAME" -no-emul-boot -boot-load-size 4 -c boot.cat -b $CDBOOT -o "$ELTORITOISO" .

		# Sector count
		sectors=$(du "$ELTORITOISO" | tail -1 | awk '{print $1}')
		size_mb=$(du -h "$ELTORITOISO" | tail -1 | awk '{print $1}')

		#echo "$ELTORITOISO has $sectors sectors, contains the boot-132 files and that has cdboot as its El Torito boot image"
		echo "created: $ELTORITOISO ($size_mb | $sectors sectors)"

	cd - > /dev/null

	#
	# Create a bootable image 
	#

	# Remove any previous copies
	#if [ -e "$TARGET" ];then
		#rm -Rf "$TARGET"
		#echo "removed: $TARGET"
	#fi


	# Default size of the bootable image to be created in Megabyte
	# FIXME check size < thinned binaryroots dir?
	# FIXME add size in pd_config
	#SIZE=$(du -h -d 0 "$SOURCE" | cut -f 1 | sed 's/M//'g) # without "M"
	#SIZE=$(expr $SIZE + $(expr 255 - $SIZE)) # add some MB to be on the safe side
	SIZE="1618" # full
	if [ "$ADD_RELEASE_NANO" = "y" ]; then
		if [ "$PUREDARWIN_RELEASE" = "nano" ]; then
			SIZE="150" # nano
		else
			SIZE="640" # bootstrap
		fi
	fi

	# Create a bootable image
	echo "Creating $TARGET (${SIZE}M)"
	# hdiutil: manipulate disk images (attach, verify, burn, etc)
	#       create  new image of the given size
	#       -fs     specify the filesystem (HFS+J <- HFS+ journalised) 
	#       -o      the result written image
	#       -size   specify the size of the image
	#       -layout specify the partition layout of the image (which is "NONE" here)
	#       -type   UDIF is the default disk image type
	#       -nospotlight (Undocumented arg)
	#               > strings /usr/bin/hdiutil| grep nospotlight
	#               -nospotlight
	#               > strings /usr/share/man/man1/hdiutil.1 | grep nospotlight
	#               >
	#hdiutil create -ov -fs HFS+J -o "$TARGET" -size ${SIZE}M -layout NONE -type UDIF -nospotlight
	#mv $TARGET.dmg $TARGET

	dd if=/dev/zero of="$TARGET" bs=1024k count=$SIZE


	# Suppress automatic mounting of any filesystems in the image
	# 	This will result in /dev entries being created and (for non-kernel-attached images)
	# 	a process in the background, but no volumes will be mounted.
	# FIXME `hdid' is not buildable nor available in Darwin, consequently the next steps are failing!
	# FIXME `hdid' fails with unknown extension as .vmwarevm or .foobar
	mv "$TARGET" "$TARGET.dmg"
	export DEVICE=$(hdid -nomount "$TARGET.dmg" |  head -1 | awk '{print $1}')
	export RDEVICE=$(echo $DEVICE | sed s/disk/rdisk/)
	mv "$TARGET.dmg"  "$TARGET"
	echo "Removed automatic mounting of any FS in $TARGET ($DEVICE entry kept)"
	
	# Alternative `nbdst' <- not available.

	# Alternative via `vndevice' works if
	# fsck -fy has been run against the volume header of the HFS partition

	echo "Initializing $RDEVICE"
	# pdisk -initialise (Undocumented arg)
	#       > strings /usr/sbin/pdisk | grep "\-initia"
        #       -initialize
	#       > strings /usr/share/man/man8/pdisk.8| grep "\-initia"
	#       >
	pdisk $RDEVICE -initialize

	echo "Partitioning $RDEVICE"
	# pdisk -dump (Undocumented arg)
	#       > strings /usr/sbin/pdisk | grep "\-dump"
        #       -initialize
	#       > strings /usr/share/man/man8/pdisk.8| grep "\-dump"
	#       >
	blocks=$(pdisk $RDEVICE -dump | grep 2: | awk -F" " '{print $4}')
	# create the partition on the image
	pdisk $RDEVICE -createPartition "$VOLNAME" Apple_HFS $sectors $(expr $blocks - $sectors) > /dev/null
	# figure out what slice the partition was created on
	slice=`pdisk $RDEVICE -dump | grep "$VOLNAME" | awk -F: '{print $1}' | awk -F" " '{print $1}'` 
	echo "Partition created on slice $slice ($blocks blocks)"


	# this is the tricky part
	# dd
	#	skip=n   Skip n blocks from the beginning of the input before copying.
	#	         On input which supports seeks, an lseek(2) operation is used.
	#                Otherwise, input data is read and discarded.
	#       seek=n   Seek n blocks from the beginning of the output before copying. 
	#       bs=n     Set both input and output block size to n bytes, superseding the ibs and obs operands.
	#
	# Partition map (with 512 byte blocks) on 'VirtualMachines/full.vmwarevm/full.iso'
	#  #:                type name    length   base    ( size )
	#  1: Apple_partition_map Apple       63 @ 1      
	#  2:          Apple_Free Extra     2664 @ 64      (  1.3M) <=== ELTORITOISO is "dd-ed" here!
	#  3:           Apple_HFS full   2524440 @ 2728    (  1.2G)
	#  4:          Apple_Free Extra       64 @ 2527168
	# Device block size=512, Number of Blocks=2527232 (1.2G)
	# DeviceType=0x0, DeviceId=0x0
	echo "ddying $ELTORITOISO to $RDEVICE"
	dd if="$ELTORITOISO" of=$RDEVICE skip=64 seek=64 bs=512

	# journaled HFS+ volume (default: yes)
	if [ ! "$ADD_HFS_JOURNAL" = "n" ]; then
		echo "Initializing ${RDEVICE}s${slice} (Journaled HFS+ volume)"
		newfs_hfs -s -J -v "$VOLNAME" ${RDEVICE}s${slice}
	else
		echo "Initializing ${RDEVICE}s${slice} (HFS+ volume)"
		newfs_hfs -s -v "$VOLNAME" ${RDEVICE}s${slice}
	fi

	echo "Mounting ${DEVICE}s${slice} on $MOUNT"
	mkdir -p "$MOUNT"
	mount -t hfs -o perm ${DEVICE}s${slice} "$MOUNT"

	# copying the boot2 HFS+ startup file 
	echo "Installing stage 2 loader (boot) to the partition's root directory"
	cp $BOOTi386/$BOOT $MOUNT/
else

	#
	# Preparing and partitionning a whole physical disk device 
	#

	# /dev/diskX passed as $1 ($TARGET)
	if [ "`ls "$TARGET" | cut -b-9`" = "/dev/disk" ]; then
		# Preventive check for disk device in /dev
		if [ ! -e "$TARGET" ]; then
			echo "ERROR: $TARGET does not exist."
			trap_handler
		fi

		# disk device node in $1 ($TARGET)
		export DEVICE=`ls "$TARGET" | cut -b-10`
		export RDEVICE=${DEVICE/disk/rdisk}
	else
		# Default disk device node linked to an existing volume (e.g. /Volumes/PureDarwin)
		PARTITION=$(df | grep "$1" | cut -d " " -f 1 ) # e.g.: /dev/disk0s2
		RPARTITION=${PARTITION/disk/rdisk}
		export DEVICE=$(echo $PARTITION | grep -o -e /dev/disk\[0-9\]\* )
		export RDEVICE=${DEVICE/disk/rdisk}
	fi

	# diskarbitrationd is not present nor needed in the "nano" and "bootstrap" releases.
	if [ -e "/System/Library/LaunchDaemons/com.apple.diskarbitrationd.plist" ]; then
		# Disable automounting in Finder and popping-up dialog boxed
		launchctl unload /System/Library/LaunchDaemons/com.apple.diskarbitrationd.plist
	fi

	export COMMAND_LINE_INSTALL=1
	umount -f ${DEVICE}s1
	#umount -f $PARTITION

	# FIXME fix needed for time
	sleep 3

	#
        # Partitioning and Bootloader 
	#

	# MBR initialisation with a template file (for BIOS) 
	#       -i initialise the MBR sector and also erase partition table (exclusiv to u)
	#       -u Update MBR code, preserving existing partition table (exclusiv to i)
	#       -y Do not ask for confirmation before writing
	#       -a Specify an automatic partitioning style (which is "hfs")
	#       -f Specifies an alternate MBR template file (which is $BOOT0)
	# Erase MBR (default: yes)
	echo "Installing boot0 to the partition MBR"
	if [ ! "$ADD_MBR_ERASE" = "n" ]; then
		fdisk -i -y -a hfs -f $BOOTi386/$BOOT0 $RDEVICE
	else
		fdisk -u -y -a hfs -f $BOOTi386/$BOOT0 $RDEVICE
	fi
	
	# Create an  HFS Plus file system
	#       -s case-sensitive HFS Plus filesystem
	#       -J journaled HFS+ volume (default journal size is 8MB)
	#       -v volume name (which is the following arg)
	# journaled HFS+ volume (default: yes)
	# FIXME "...s1" should not be hardcoded
	if [ ! "$ADD_HFS_JOURNAL" = "n" ]; then
		/sbin/newfs_hfs -s -J -v "$VOLNAME" ${RDEVICE}s1
	else
		/sbin/newfs_hfs -s -v "$VOLNAME" ${RDEVICE}s1
	fi
	# 
	sleep 5 # FIXME fix needed for time / absolutely needed!

	echo "Installing stage 1 booter (boot1h) to the partition bootsector"
	dd if=$BOOTi386/$BOOT1H of=${RDEVICE}s1 

	sleep 3 # FIXME fix needed for time

	# Add Chameleon bootloader (default: yes)
	if [ "$ADD_CHAMELEON" = "n" ]; then
		# startupfiletool should not be needed with Chameleon
		$DIRNAME/../scripts/startupfiletool ${RDEVICE}s1 $BOOTi386/$BOOT
	fi

	# TODO RAID Install

	/bin/sync

	# Force the mount point to be $MOUNT before diskarbitrationd is launched again
	mkdir -p ${MOUNT}
	mount -t hfs ${DEVICE}s1 ${MOUNT}

	# copying the boot2 HFS+ startup file 
	echo "Installing stage 2 loader (boot) to the partition's root directory"
	cp $BOOTi386/$BOOT $MOUNT/

	# FIXME?
	# ./fdisk -e /dev/rdiskX
	# f 1
	# w
	# q

	# diskarbitrationd is not present nor needed in the "nano" and "bootstrap" releases.
	if [ -e "/System/Library/LaunchDaemons/com.apple.diskarbitrationd.plist" ]; then
		# Enable "automounting in Finder and popping-up dialog boxed" on Mac OS X host
		launchctl load /System/Library/LaunchDaemons/com.apple.diskarbitrationd.plist
	fi	
fi	

# Disable Spotlight
echo "Disabling Spotlight indexation"
touch ${MOUNT}/.metadata_never_index

# Adopts (activates) on-disk ownership
# FIXME deprecated.
echo "Adopting (Activating) on-disk ownership"
vsdbutil -a ${MOUNT}

# Ensure permissions are on
# FIXME seems to always fail and make the set -e strict mode also.
#vsdbutil -c ${MOUNT}

###############################################################################
# BINARYROOTS DEPLOYMENT 
###############################################################################

# Moving to the PureDarwin root ("/")
cd ${MOUNT}

mkdir -p ./private/var/log/
echo "Installing packages on '${MOUNT}'..."

for PROJECT in `cat $DIRNAME/$BINARYROOTS_LIST_FILE` ; do
	echo " * $(basename $PROJECT.root.tar.bz2)"

	# (default: n)
	if [ "$ADD_RELEASE_NANO" = "y" ]; then
		tar xjpf $PACKAGES/$PROJECT.root.tar.bz2 \
			--exclude '*svn*' \
			--exclude '*/include/*' \
			--exclude '/Developer' \
			--exclude '/AppleInternal' \
			--exclude '/usr/lib/libSystem.B_debug.dylib' \
			--exclude '/usr/lib/libSystem.B_profile.dylib' \
 			--exclude '*.h' >> ${MOUNT}/private/var/log/pd_setup.log
			#--exclude '/usr/local/lib/*' \
	else	
		tar xjpf $PACKAGES/$PROJECT.root.tar.bz2 >> ${MOUNT}/private/var/log/pd_setup.log
	fi
done

echo 

###############################################################################
# MISSING STUFF (mainly vital binarydrivers of darwin 10)
###############################################################################

# 	fixme: "until" is commented because missingstuff shouldn't miss stuff.
# 	It happens (stuff is missed) if the target dir or file exists, even partially.
# 	(e.g., CoreFoundation.framework)
#	note: no missingstuff in "nano" release

missingstuff() {
	until [ -e ${MOUNT}/$1 ]; do 
		echo "WARNING! $1 is missing. Do you want to copy it from your start volume?"
		echo "You will not be allowed to use the resulting installation anywhere else but on your Apple-labeled computer. Please check with the Mac OS X license first."
		printf "Copy? y[n] "
		read CONT
		if [ "$CONT" = "y" ]; then 
			ditto -v $1 ${MOUNT}/$1 #--rsrc --extattr 
		fi
	done
}	

# FIXME IOKitUser built in 9J61 lacks of symbol as _kextmanager* needed by kextload..
# The one from 9F33pd1/IOKitUser.root.tar.gz is OK!

#if [ "$DARWIN_RELEASE" = "10" ]; then
	# Disabled for obvious reasons.
#	missingstuff /System/Library/Extensions/AppleACPIPlatform.kext
#	missingstuff /System/Library/Extensions/IOSCSIArchitectureModelFamily.kext
#	missingstuff /System/Library/Extensions/AppleRTC.kext
#	missingstuff /System/Library/Extensions/IOATAFamily.kext
#	missingstuff /System/Library/Extensions/IOPCIFamily.kext

#fi

# Add Chameleon themes (default: yes)
#if [ ! "$ADD_CHAMELEON_THEMES" = "n" ]; then
	# FIXME populate Extra folder, and custom plist + adapt graphics resolution
	# http://forum.voodooprojects.org/index.php/topic,388.0.html
#fi

# Voodoo kernel (xnu-dev) replacement (default: y)
if [ ! "$ADD_VOODOO_XNU" = "n" ]; then
	#
	# Sources: http://code.google.com/p/xnu-dev/
	#
	echo " * Voodoo_kernel.root.tar.bz2"
	tar xjpf $PACKAGES/Voodoo_kernel.root.tar.bz2 >> ${MOUNT}/private/var/log/pd_setup.log 

	# Keeping the "vanilla" kernel
	mv $MOUNT/mach_kernel $MOUNT/mach_kernel.origin

	# mach_kernel.voodoo.9.5 (Voodoo 1.0 Rev A / xnu-dev) (default: y)
	if [ ! "$ADD_VOODOO_XNU_9_5_0" = "n" ]; then
		cp $MOUNT/mach_kernel.voodoo.9.5 $MOUNT/mach_kernel
	fi

	# mach_kernel.voodoo.9.7 (Voodoo 2 -- alpha 3 -- (based on XNU 9.7.0, for Intel only) (default: n)
	if [ "$ADD_VOODOO_XNU_9_7_0" = "y" ]; then
		cp $MOUNT/mach_kernel.voodoo.9.7 $MOUNT/mach_kernel
	fi
fi

# Xnu-speedstep support (default: n)
if [ "$ADD_VOODOO_XNU_SPEEDSTEP" = "y" ]; then
	# "A kernel extension for OS X to enable Intel SpeedStep and undervolting on any kernel"
	# 
	# Intel SpeedStep driver which extends the range of CPUs and motherboard support
	# AppleIntelCPUPowerManagement kext
	# http://code.google.com/p/xnu-speedstep
	# v1.4.9
	echo " * VoodooIntelEnhancedSpeedStep.root.tar.bz2"
	tar xjpf $PACKAGES/VoodooIntelEnhancedSpeedStep.root.tar.bz2 >> ${MOUNT}/private/var/log/pd_setup.log 

	chown -R root:wheel ${MOUNT}/System/Library/Extensions/IntelEnhancedSpeedStep.kext
	chmod -R 755 $MOUNT/System/Library/Extensions/IntelEnhancedSpeedStep.kext

	# Which frequencies are available: sysctl kern.cputhrottle_freqs
	# switch frequency               : sudo sysctl -w kern.cputhrottle_curfreq=YYYY
fi

# VoodooPowerMini Kext (v 1.2.4) support (default: n)
if [ "$ADD_VOODOO_POWER_MINI" = "y" ]; then
	# "OSX Alternative Power Management"
	# 
	# http://code.google.com/p/voodoo-power
	# http://www.superhai.com/darwin.html
	echo " * VoodooPowerMini.root.tar.bz2"
	tar xjpf $PACKAGES/VoodooPowerMini.root.tar.bz2 >> ${MOUNT}/private/var/log/pd_setup.log 
fi
# FIXME add choice for:
#VoodooBattery.kext - To be used with vanilla ACPI and pm.bundle, 10.5.x
#VoodooPower Kext
#VoodooPower Command Line Interface Tool
#VoodooUSBEHCI for 10.5.x see readme!



# VoodooPS2Controller 0.98 support (default: y)
if [ ! "$ADD_VOODOO_PS2CONTROLLER" = "n" ]; then
	# WARNING: conflict with ACPIPS2Nub!
	#
	# Contains:
	#  - VoodooPS2Controller
	#  - VoodooPS2Keyboard
	#  - VoodooPS2Mouse
	#  - VoodooPS2Trackpad
	# c.f. Contents/Plugins/VoodooPS2Trackpad.kext/Info.plist
	# 
	# FIXME synapticsconfigload <- needed? functional?
	# FIXME in vmx? <- keyboard.vusb.enable = "FALSE"
	echo " * VoodooPS2Controller.root.tar.bz2"
	tar xjpf $PACKAGES/VoodooPS2Controller.root.tar.bz2 >> ${MOUNT}/private/var/log/pd_setup.log 
fi

# David Elliott PS2 support (default: n)
if [ "$ADD_DFE_PS2CONTROLLER" = "y" ]; then
	# ACPIPS2Nub: PS2Controller for mouse matching a PNP device from David Elliott 
	# org.tgwbd.driver.ACPIPS2Nub
	# version 1.0.0d1
	echo " * ACPIPS2Nub.root.tar.bz2 (Copyright David Elliott, 2007)"
	tar xjpf $PACKAGES/ACPIPS2Nub.root.tar.bz2 >> ${MOUNT}/private/var/log/pd_setup.log 

	echo " * ApplePS2Controller.root.tar.bz2"
	tar xjpf $PACKAGES/ApplePS2Controller.root.tar.bz2 >> ${MOUNT}/private/var/log/pd_setup.log 
fi

# Prompt for VMware support (default: y)
if [ ! "$ADD_VMWARE" = "n" ]; then
	# Fake easily guest OS detection (Mac OS X Server) in Fusion
	# 	Template for a PureDarwin binary root:
	# 	/System/Library/CoreServices/ServerVersion.plist
	# 	/System/Library/CoreServices/SystemVersion.plist
	# Info: http://code.google.com/p/puredarwin/issues/detail?id=3

	# FIXME repack or at least move the archive elsewhere than in pd_setup_files
	# LegacyAppleIntelPIIXATA and NullCPUPowerManagement KEXTs for use with VMware other than Fusion 
	echo " * VMware-Drivers-OpenSource.zip"
	unzip -q $DIRNAME/pd_setup_files/VMware-Drivers-OpenSource.zip -d ${MOUNT}/System/Library/Extensions

	# (default: n)
	if [ "$ADD_X" = "y" ]; then
		# Graphic drivers required for X display
		echo " * VMwareIOFramebuffer.kext.zip"
		unzip -q $DIRNAME/pd_setup_files/VMwareIOFramebuffer.kext.zip -d ${MOUNT}/System/Library/Extensions
	fi	
fi

# PureFoundation enhancements (default: y)
if [ ! "$ADD_PUREFOUNDATION" = "n" ]; then
	#echo "Installing PureFoundation enhancements"
	#rm -rf $MOUNT/System/Library/Frameworks/CoreFoundation.framework
	# PureFoundation 0.003.1 (svn rev 30)
	# 	SHA1 Checksum: b0bc7432627a060874f28f04297a80c4a5fbd094
	# 	CoreFoundation and ddistnoted
	# 	PureFoundation-0.003.1.root.zip 
	echo " * PureFoundation.root.tar.bz2 (Foundation, CoreFoundation and ddistnoted)"
	tar xjpf $PACKAGES/PureFoundation.root.tar.bz2 >> ${MOUNT}/private/var/log/pd_setup.log 
	# WORKAROUND
	# FIXME remove workaround
	# Because otool -L /Volumes/PureDarwin/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation 
	#	/Volumes/PureDarwin/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation:
	#	/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation (compatibility version 150.0.0, current version 476.0.0)
	#  ---> /Users/stuart/Library/Frameworks/Foundation.framework/Versions/C/Foundation (compatibility version 300.0.0, current version 300.0.0)
	#	/usr/lib/libicucore.A.dylib (compatibility version 1.0.0, current version 36.0.0)
	mkdir -p "$MOUNT/Users/stuart/Library/Frameworks"
	chroot "$MOUNT" ln -fs /System/Library/Frameworks/Foundation.framework /Users/stuart/Library/Frameworks/Foundation.framework
	
	# ddistnoted content is provided in PureFoundation archive too
	echo " * ddistnoted.root.tar.bz2"
	tar xjpf $PACKAGES/ddistnoted.root.tar.bz2 >> ${MOUNT}/private/var/log/pd_setup.log 

	# Usefull for passwd (and dscl (and sudo?))
	#rm -R ${MOUNT}/System/Library/PrivateFrameworks/OpenDirectory.framework/Versions/A/Frameworks
	echo " * CFOpenDirectory.root.tar.bz2"
	mkdir -p ${MOUNT}/System/Library/PrivateFrameworks/OpenDirectory.framework/Versions/A/Frameworks
	tar xjpf $PACKAGES/CFOpenDirectory.root.tar.bz2 >> ${MOUNT}/private/var/log/pd_setup.log 

	# configd stuff for network support 
	# Source: https://sites.google.com/a/puredarwin.org/puredarwin/developers/network
	#         on Mar 7, 2009 8:25 PM by stuart@echus.demon.co.uk (version 3 / earlier versions)
	echo " * configd.root.tar.bz2"
	tar xjpf $PACKAGES/configd.root.tar.bz2 >> ${MOUNT}/private/var/log/pd_setup.log 

	# Satisfy dependencies for bootp (bootp popuplate /System/Library/SystemConfiguration with IPConf.. & co)
	# bootp is now added in pd_roots
	echo " * NotApple80211.root.tar.bz2"
	tar xjpf $PACKAGES/NotApple80211.root.tar.bz2 >> ${MOUNT}/private/var/log/pd_setup.log 
	
	# CFNetwork.framework and CarbonCore.framework (only headers) wrapped inside CoreServices.framework
	# Source: https://sites.google.com/a/puredarwin.org/puredarwin/developers/cfnetwork
	#         on Feb 23, 2009 6:10 PM by stuart@echus.demon.co.uk (version 1)
	echo " * CFNetwork.root.tar.bz2 (wrapped in CoreServices.framework)"
	tar xjpf $PACKAGES/CFNetwork.root.tar.bz2 >> ${MOUNT}/private/var/log/pd_setup.log 

	# configd_plugins-91.root (partially built)
	#
	# 	InterfaceNamer.bundle <- ?
	#	KernelEventMonitor.bundle <- dhcp client (according to qemu user mode network stack
	#	Kicker.bundle <- ???
	#cp -R /Users/aladin/PureDarwin/darwinbuild/9J61/.build/buildroot.nfs/private/var/tmp/configd_plugins/configd_plugins-91.root/System/Library/SystemConfiguration/KernelEventMonitor.bundle $MOUNT/System/Library/SystemConfiguration/
	echo " * configd_plugins.root.tar.bz2 (InterfaceNamer.bundle, KernelEventMonitor.bundle and Kicker.bundle)"
	tar xjpf $PACKAGES/configd_plugins.root.tar.bz2 >> ${MOUNT}/private/var/log/pd_setup.log 

	chown -R root:wheel $MOUNT/System/Library/LaunchDaemons/

	# FIXME ? + /Library/Preferences/SystemConfiguration/preferences.plist
fi

# User login support (default: y)
if [ ! "$ADD_LOGIN" = "n" ]; then
	# multi-user - temporary workaround mode (small PAM module for session)
	#
	# 	Source: https://sites.google.com/a/puredarwin.org/puredarwin/users/users
	#	        https://sites.google.com/a/puredarwin.org/puredarwin/downloads
	#
	echo " * pam_sessioncreate.root.tar.bz2"
	tar xjpf $PACKAGES/pam_sessioncreate.root.tar.bz2 >> ${MOUNT}/private/var/log/pd_setup.log 
	# FIXME should it be integrated into "pam_modules" ?
	# FIXME + cat >${MOUNT}/etc/pam.d/login<<EOOF

	# PC/SC stack
	#
	# Contain:
	#  - System/Library/Frameworks/PCSC.framework
	#  - usr/sbin/pcscd
	echo " * PCSC.root.tar.bz2"
	tar xjpf $PACKAGES/PCSC.root.tar.bz2 >> ${MOUNT}/private/var/log/pd_setup.log 
fi

# FIXME add MacPorts sources & bin? archive? 

# Add MacPorts tcl requirements (default: y)
if [ ! "$ADD_MACPORTS_TCL" = "n" ]; then
	# Needed in order to be able to compile MacPorts and probably with it.
	echo " * tcl-8.5.6_0+threads.i386.tbz2"
	tar xjpf $DIRNAME/$BINARYROOTS_DEFAULT_DIR/mp/tcl-8.5.6_0+threads.i386.tbz2 >> ${MOUNT}/private/var/log/pd_setup.log
fi

# FIXME archive
# Add X and co (default: no)
if [ "$ADD_X" = "y" ]; then
	# Installing X binaryroots from macports (windowmaker, fluxbox, wmii, eterm, etc..)
	for f in `ls $DIRNAME/$BINARYROOTS_DEFAULT_DIR/X/*.tbz2` ; do
		echo " * $(basename $f)"
		tar xjpf $f >> ${MOUNT}/private/var/log/pd_setup.log
	done
 
	# Removing MacPorts archive "noise" (+COMMENT +CONTENTS +DESC +PORTFILE and +STATE in /)
	rm -f "${MOUNT}/+*"

	# Prevent error: "Fontconfig error: Cannot load default config file" which "cycles" X
	chroot ${MOUNT} /usr/X11R6/bin/fc-cache -v -f /usr/X11R6/lib/X11/fonts/
fi

# DTrace facility (default: n)
#
# 	DTrace is not present on http://src.macosforge.org/Roots/
# 	Notice Foundation.framework and CoreFoundation.framework dependencies
#
# 	What about "Symbolication.framework"? (problem with 9J61 (not patched as 9F33pd1))
#
if [ "$ADD_DTRACE" = "y" ]; then

	echo " * dtrace.root.tar.bz2"
	tar xjpf $PACKAGES/dtrace.root.tar.bz2 >> ${MOUNT}/private/var/log/pd_setup.log

	#missingstuff /usr/sbin/dtrace
	#missingstuff /System/Library/PrivateFrameworks/Symbolication.framework
	#missingstuff /usr/lib/libdtrace.dylib
	#missingstuff /usr/bin/dtruss
	#missingstuff /usr/bin/procsystime
fi

# MacFUSE userland filesystem (default: n)
if [ "$ADD_MACFUSE" = "y" ]; then

	# MacFUSE 2.0 - Version 2.0.3.2 
	echo " * MacFUSE.root.tar.bz2"
	tar xjpf $PACKAGES/MacFUSE.root.tar.bz2 >> ${MOUNT}/private/var/log/pd_setup.log
	
	chown -R root:wheel ${MOUNT}/Library/Filesystems/fusefs.fs 
	chmod -R 755 ${MOUNT}/Library/Filesystems/fusefs.fs

	# FIXME TODO add binaryroots to uncomment below
	# sshfs in MacFUSE  (default: n)
#	if [ "$ADD_MACFUSE_SSHFS" = "y" ]; then
#		echo " * MacFUSE_sshfs.root.tar.bz2"
#		curl "http://macfuse.googlecode.com/svn/trunk/filesystems/sshfs/binary/sshfs-static-leopard" > ${MOUNT}/usr/sbin/mount_sshfs
#		chmod a+x ${MOUNT}/usr/sbin/mount_sshfs
#	fi

	# ramdisk in MacFUSE  (default: n)
	if [ "$ADD_MACFUSE_RAMDISK" = "y" ]; then
		echo " * MacFUSE_ramdisk.root.tar.bz2"
		tar xjpf $PACKAGES/MacFUSE_ramdisk.root.tar.bz2 >> ${MOUNT}/private/var/log/pd_setup.log
	fi

fi


cd - > /dev/null

###############################################################################
# SELF DEPLOYMENT (bootstrap) 
###############################################################################

# Clone the setup scripts repository to the target? (default: n)
if [ "$ADD_CLONE" = "y" ]; then
	echo "Copying setup files..."
	mkdir -p ${MOUNT}/usr/local/share/puredarwin/setup/$TEMPDIR
	# Warning: read `hg help clone' (e.g. incompatible with mq)
	# -l not supported on Darwin and Mac OS X
	# -a not supported on Darwin..
	#cp -Rfp $DIRNAME/.. ${MOUNT}/usr/local/share/puredarwin
	cp -Rfp $DIRNAME/../APPLE_DRIVER_LICENSE.txt 	${MOUNT}/usr/local/share/puredarwin/
	cp -Rfp $DIRNAME/../APPLE_LICENSE.txt		${MOUNT}/usr/local/share/puredarwin/
	cp -Rfp $DIRNAME/../PUREDARWIN_LICENSE.txt	${MOUNT}/usr/local/share/puredarwin/
	cp -Rfp $DIRNAME/../WELCOME			${MOUNT}/usr/local/share/puredarwin/
	cp -Rfp $DIRNAME/../patches			${MOUNT}/usr/local/share/puredarwin/
	cp -Rfp $DIRNAME/../plists			${MOUNT}/usr/local/share/puredarwin/
	cp -Rfp $DIRNAME/../projects			${MOUNT}/usr/local/share/puredarwin/
	cp -Rfp $DIRNAME/../scripts			${MOUNT}/usr/local/share/puredarwin/

	cp -fp $DIRNAME/../setup/*			${MOUNT}/usr/local/share/puredarwin/setup/ 2> /dev/null

	# c.f. pd_config: DESTDIR="$TEMPDIR/Packages_D${DARWIN_RELEASE}_${ARCH}"
	cp -Rfp $DIRNAME/../setup/pd_setup_files	${MOUNT}/usr/local/share/puredarwin/setup/

	# FIXME below should disappear (with deps)
	# An arbitrary mountpoint potentially usefull on read-only mode
	mkdir -p ${MOUNT}/Volumes/PureDarwin
	# Idem
	mkdir -p ${MOUNT}/tmp/i386

fi

# Add setup binaryroots to the target? (default: n)
if [ "$ADD_CLONE_PACKAGES" = "y" ]; then

	# e.g., DESTDIR="Packages_D9_i386" and TEMPDIR="pd_tmp"
	cp -Rfp $DIRNAME/../setup/$DESTDIR		${MOUNT}/usr/local/share/puredarwin/setup/$TEMPDIR/

	# Specific for X roots
	mkdir -p ${MOUNT}/usr/local/share/puredarwin/setup/$BINARYROOTS_DEFAULT_DIR
	cp -Rfp $DIRNAME/../setup/$BINARYROOTS_DEFAULT_DIR/mp	${MOUNT}/usr/local/share/puredarwin/setup/$BINARYROOTS_DEFAULT_DIR/
	cp -Rfp $DIRNAME/../setup/$BINARYROOTS_DEFAULT_DIR/X	${MOUNT}/usr/local/share/puredarwin/setup/$BINARYROOTS_DEFAULT_DIR/

	cp -Rfp $DIRNAME/../setup/$DESTDIR		${MOUNT}/usr/local/share/puredarwin/setup/$TEMPDIR/
	
	# Alternative if a mercurial binary root is available (including its dependencies..) 
	#hg clone $DIRNAME/.. ${MOUNT}/usr/local/share/puredarwin
	# Can take a lot of disk space
	#hg clone $DIRNAME/$TEMPDIR ${MOUNT}/usr/local/share/puredarwin/$TEMPDIR
fi

###############################################################################
# SETTING FILES DEPLOYMENT
###############################################################################

echo "Copying settings files..."
# default: y
if [ "$ADD_SETTINGS_FILES" = "n" ]; then
	# FIXME not sure we need all of them for nano
	mkdir -p ${MOUNT}/Library/Preferences/SystemConfiguration/
	cp -fp $DIRNAME/../projects/PureDarwinSettings/Library/Preferences/SystemConfiguration/com.apple.Boot.plist ${MOUNT}/Library/Preferences/SystemConfiguration/com.apple.Boot.plist

	mkdir -p ${MOUNT}/System/Library/LaunchDaemons/
	cp -fp $DIRNAME/../projects/PureDarwinSettings/System/Library/LaunchDaemons/com.apple.getty.plist ${MOUNT}/System/Library/LaunchDaemons/com.apple.getty.plist
	cp -fp $DIRNAME/../projects/PureDarwinSettings/System/Library/LaunchDaemons/org.puredarwin.nanoshell.plist ${MOUNT}/System/Library/LaunchDaemons/org.puredarwin.nanoshell.plist
	cp -fp $DIRNAME/../projects/PureDarwinSettings/System/Library/LaunchDaemons/org.puredarwin.installer.plist ${MOUNT}/System/Library/LaunchDaemons/org.puredarwin.installer.plist

	mkdir -p ${MOUNT}/etc/
	cp -fp $DIRNAME/../projects/PureDarwinSettings/etc/ttys ${MOUNT}/etc/ttys
	cp -fp $DIRNAME/../projects/PureDarwinSettings/etc/zshrc ${MOUNT}/etc/zshrc
	cp -fp $DIRNAME/../projects/PureDarwinSettings/etc/bashrc ${MOUNT}/etc/bashrc

	mkdir -p ${MOUNT}/System/Library/CoreServices/
	touch ${MOUNT}/System/Library/CoreServices/ServerVersion.plist

	mkdir -p ${MOUNT}/var/db/dslocal/nodes/Default/users
	cp -fp $DIRNAME/../projects/PureDarwinSettings/var/db/dslocal/nodes/Default/users/root.plist ${MOUNT}/var/db/dslocal/nodes/Default/users/root.plist

	# APPLE_DRIVER_LICENSE.txt, APPLE_LICENSE.txt and PUREDARWIN_LICENSE.txt
	# FIXME how to handle that correctly?
	cp -fp $DIRNAME/../projects/PureDarwinSettings/*LICENSE.txt ${MOUNT}/
else
	# Copying all settings files
	cp -fpR  $DIRNAME/../projects/PureDarwinSettings/* ${MOUNT}/
fi

###############################################################################
# EFI BOOTLOADER
###############################################################################

# Copy bootloader files for bless (usefull for pd_make_dmg)
mkdir -p $MOUNT/usr/standalone/i386/ 
cp $BOOTi386/* $MOUNT/usr/standalone/i386/

if [ ! -e "$MOUNT/System/Library/CoreServices" ]; then
	echo "WARNING! $MOUNT/System/Library/CoreServices is missing, but it is needed for EFI booting."
	#exit 1
fi

if [ ! -e "$MOUNT/usr/standalone/i386/cdboot" ]; then
	echo "WARNING! $MOUNT/usr/standalone/i386/cdboot is missing, but it is needed for BIOS booting."
	#exit 1
fi

#${MOUNT}/usr/sbin/bless -verbose -folder "$MOUNT/System/Library/CoreServices" -bootinfo -bootefi 
# --folder   Set this directory to be the Mac OS X/Darwin blessed directory, containing a BootX secondary loader for New World machines
# --bootinfo Create a BootX file in the Darwin system folder using file as a source.
#            If file is not provided, a default is used (see FILES), using a path relative
#            to the mountpoint you are blessing.
#            This attempts to ensure that a BootX is used that is compatible with the OS on the target volume.
# --bootefi  Create a boot.efi file in the Mac OS X/Darwin system folder using file as a source
#            [...]
echo "Blessing $MOUNT/System/Library/CoreServices"
${MOUNT}/usr/sbin/bless --folder "$MOUNT/System/Library/CoreServices" --bootinfo --bootefi --verbose
#${MOUNT}/usr/sbin/bless --folder "$MOUNT/System/Library/CoreServices" --bootefi --verbose


# Use a little resolution (default: n)
# TODO alter com.apple.Boot.plist
if [ "$ADD_FB_640x480x32" = "y" ]; then
	GRAPHICS_MODE="\"Graphics Mode\"=\"640x480x32\""
fi

# Use a medium resolution (default: y)
# TODO alter com.apple.Boot.plist
if [ ! "$ADD_FB_800x600x32" = "n" ]; then
	GRAPHICS_MODE="\"Graphics Mode\"=\"800x600x32\""
fi

# Use a normal resolution (default: n)
# TODO alter com.apple.Boot.plist
if [ "$ADD_FB_1024x768x32" = "y" ]; then
	GRAPHICS_MODE="\"Graphics Mode\"=\"1024x768x32\""
fi

###############################################################################
# TIMEZONE 
###############################################################################

# FIXME which one as default?
# Setting GMT+1 timezone (instead of Pacific)
rm -f ${MOUNT}/private/etc/localtime
#chroot ${MOUNT} ln -s /usr/share/zoneinfo/Europe/Berlin /private/etc/localtime
# [...]
#chroot ${MOUNT} ln -s /usr/share/zoneinfo/Europe/London /private/etc/localtime
# [...]
chroot ${MOUNT} ln -fs /usr/share/zoneinfo/Europe/Paris /private/etc/localtime

# Preparing /etc/hostconfig (deprecated?)
echo "CRASHREPORTER=-NO-" >> $MOUNT/private/etc/hostconfig

# Encrypting swap by default 
# FIXME: it seems dynamic_pager lacks -E even with ENCRYPTSWAP=-YES
echo "ENCRYPTSWAP=-YES-" >> $MOUNT/private/etc/hostconfig

###############################################################################
# SYSCTL 
###############################################################################

# Setting hostname
echo "kern.hostname=PureDarwin.local" > $MOUNT/private/etc/sysctl.conf

###############################################################################
# LOGIN PROMPT 
###############################################################################

# Message Of The Day 
echo "Welcome to PureDarwin!" > $MOUNT/private/etc/motd
echo '' >> ${MOUNT}/private/etc/motd

###############################################################################
# SHELLS 
###############################################################################

# dyld errors
#
# com.apple.dyld[76]: update_dyld_shared_cache[76] for arch=i386 failed: /var/db/dyld/shared_region_roots/ does not exist, errno=2
mkdir -p ${MOUNT}/var/db/dyld/shared_region_roots
# com.apple.dyld[50]: update_dyld_shared_cache: warning, no entries found in shared_region_roots
echo "/bin/sh"   >  ${MOUNT}/var/db/dyld/shared_region_roots/Applications.paths

# Add the Bash shell as default shell? (default: y)
if [ ! "$ADD_BASH" = "n" ]; then
	chroot ${MOUNT} ln -fs /bin/bash /bin/sh
	echo "/bin/bash" >> ${MOUNT}/var/db/dyld/shared_region_roots/Applications.paths
	
fi

# Populate (or remove) /etc/bashrc (default: y)
if [ "$ADD_BASHRC" = "n" ]; then
	rm -f ${MOUNT}/etc/bashrc
fi

# Add the Z shell as default shell? (default: n)
if [ "$ADD_ZSH" = "y" ]; then
	chroot ${MOUNT} ln -fs /bin/zsh /bin/sh
	echo "/bin/zsh"  >> ${MOUNT}/var/db/dyld/shared_region_roots/Applications.paths
fi

# Populate (or remove) /etc/zshrc (default: y)
if [ "$ADD_ZSHRC" = "n" ]; then
	rm -f ${MOUNT}/etc/zshrc
fi

###############################################################################
# MINOR ERRORS FIXES
###############################################################################

echo "Fixing minor errors"

# Avoid orphan link of /etc/resolv.conf
touch ${MOUNT}/private/var/run/resolv.conf

# com.apple.dyld[50]: update_dyld_shared_cache: warning, empty cache not generated for arch i386
#   -root  specifies the root of an OS installation for which dyld's shared cache should be updated
#   -arch  generates cache files for the specified one (i386)
#   -force regenerated the shared cache files even if they appear to be already up-to-date
#
# FIXME warning, could not bind /Volumes/PD/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation...
# ...because realpath() failed on /Volumes/PD/Users/stuart/Library/Frameworks/Foundation.framework/Versions/C/Foundation

# FIXME ./pd_setup: line 1138: /Volumes/bootstrap: is a directory

#if [ "$DARWIN_RELEASE" = "9" ]; then
	#${MOUNT} update_prebinding -root ${MOUNT} -arch i386 -force		# Available in Leopard
	#${MOUNT} update_prebinding -root ${MOUNT} -arch i386 -force -debug 
#else
	#${MOUNT} update_dyld_shared_cache -root ${MOUNT} -arch i386 -force	# Available in SnowLeopard
#fi

# com.apple.launchd[1] (org.ntp.ntpd): Unknown key: SHAuthorizationRight
#
# 	A project at Apple is overloading the launchd configuration file   
# 	schema to store non-launchd preferences. We hope to resolve this   
# 	matter in the next major version of Mac OS X.
#
# 	Key (temporary) disabled to keep "Pure" log.
#
# cat >${MOUNT}/System/Library/LaunchDaemons/org.ntp.ntpd.plist<<EOOF

# Problem: _CFGetHostUUIDString: unable to determine UUID for host. Error: 35
# Solution: A MAC address from an attached network interface should do the trick too.
# Pseudo-solution: Adding AppleEFINVRAM (CREDITS: XSource) via:
#missingstuff /System/Library/Extensions/AppleEFIRuntime.kext 

################################################################################
# DEBUG
################################################################################

# Crank up the debug logging on launchd (default: yes). Credit: kvv for the tips.
if [ ! "$ADD_DEBUG" = "n" ]; then
	echo "log level debug" > ${MOUNT}/etc/launchd.conf
	echo "*.debug /var/log/syslog" >> ${MOUNT}/etc/syslog.conf
fi

############################################################################### 
# COPYING UTILS, FUTILS AND INUTILS! 
###############################################################################

mkdir -p ${MOUNT}/usr/local/sbin/
mkdir -p ${MOUNT}/usr/local/share/puredarwin/scripts
mkdir -p ${MOUNT}/usr/local/share/puredarwin/setup/pd_setup_files/


# Copy startupfiletool
echo "Copying startupfiletool"
cp $DIRNAME/pd_setup_files/startupfiletool ${MOUNT}/usr/local/share/puredarwin/setup/pd_setup_files/

# Copy PureDarwin scripts 
echo "Copying PureDarwin scripts"
cp $DIRNAME/../scripts/pd_* ${MOUNT}/usr/local/share/puredarwin/scripts/

# Moar futils
#cp $DIRNAME/../projects/pd_xkp/pd_xkp ${MOUNT}/usr/local/sbin/

###############################################################################
# USER MANAGEMENT
###############################################################################

# multi-user - temporary workaround mode (securityd in single thread mode (it works with some threads))
#
# 	Source : https://sites.google.com/a/puredarwin.org/puredarwin/users/users
#
# + cat >${MOUNT}/System/Library/LaunchDaemons/com.apple.securityd.plist<<EOOF

# Root account (disabled)
#
# 	Enabling root is dangerous and not recommended,
#	we do not provide root password! `sudo' should be for 
#       priviledge elevation purpose.
#
mkdir -p ${MOUNT}/var/db/dslocal/nodes/Default/users
# + cat >${MOUNT}/var/db/dslocal/nodes/Default/users/root.plist<<EOOF

# Creating default user account (default: y)
#       username: toor
#       password: toor
#
if [ ! "$ADD_DEFAULT_USER" = "n" ]; then
	echo "Creating default user (toor:toor)"
	# pd_injectuser (salter SHA-1 digest by default, should work into single user mode)
	# FIXME update pd_adduser..		
	chroot $MOUNT /usr/local/share/puredarwin/scripts/pd_injectuser / toor 
	# pd_adduser must be run on Darwin/Mac OS X host, or in single user mode from PureDarwin
	# Note: `dscl' and `passwd' dependencies must be satistified.
	# $DIRNAME/../scripts/pd_adduser
fi

###############################################################################
# X11
###############################################################################

# Add X and co (default: no)
if [ "$ADD_X" = "y" ]; then
	# Default keymapping
	cp $MOUNT/System/Library/Keyboards/USA.keymapping $MOUNT/System/Library/Keyboards/USA.keymapping.orig
	rm -f $MOUNT/System/Library/Keyboards/USA.keymapping

	# Belge keymapping (default: n)
	if [ "$ADD_KEYMAP_BELGE" = "y" ]; then
		chroot $MOUNT ln -fs /System/Library/Keyboards/Belge.keymapping /System/Library/Keyboards/USA.keymapping
	fi
	# Deutsch keymapping (default: n)
	if [ "$ADD_KEYMAP_DEUTSCH" = "y" ]; then
		chroot $MOUNT ln -fs /System/Library/Keyboards/Deutsch.keymapping /System/Library/Keyboards/USA.keymapping
	fi
	# Francais keymapping (default: n)
	if [ "$ADD_KEYMAP_FRANCAIS" = "y" ]; then
		chroot $MOUNT ln -fs /System/Library/Keyboards/Francais.keymapping /System/Library/Keyboards/USA.keymapping
	fi
	# UK keymapping (default: n)
	if [ "$ADD_KEYMAP_UK" = "y" ]; then
		chroot $MOUNT ln -fs /System/Library/Keyboards/UK.keymapping /System/Library/Keyboards/USA.keymapping
	fi
	# USA keymapping (default: y)
	if [ ! "$ADD_KEYMAP_USA" = "n" ]; then
		mv $MOUNT/System/Library/Keyboards/USA.keymapping.orig $MOUNT/System/Library/Keyboards/USA.keymapping
	fi
fi

###############################################################################
# X11 WMs
###############################################################################

# WindowMaker (default: n)
if [ "$ADD_WMAKER" = "y" ]; then
	chroot ${MOUNT} /opt/local/bin/wmaker.inst
	cp $DIRNAME/pd_setup_files/*png $MOUNT/var/root/GNUstep/Library/WindowMaker/Backgrounds
fi

#echo " 0 - WindowMaker 0.92"
#echo " 1 - Fluxbox 1.1.0.1_0"
#echo " 2 - wmii-3.1_0"

###############################################################################
# NANO LAUNCHD, DAEMONS AND PLISTS
###############################################################################

# Add launchd (default: yes)
if [ "$ADD_LAUNCHD" = "n" ]; then 
	# Overwrite /sbin/launchd with a trivial shell script 
	mkdir -p ${MOUNT}/sbin/
	cp $DIRNAME/../scripts/pd_nanoshell ${MOUNT}/sbin/launchd
	chown root:wheel ${MOUNT}/sbin/launchd
	chmod 755 ${MOUNT}/sbin/launchd
else

	# Add default login prompt (default: yes)
	if [ "$ADD_LAUNCHD_GETTY" = "n" ]; then 
		# Disable login prompt
		rm -f ${MOUNT}/System/Library/LaunchDaemons/com.apple.getty.plist
	fi

	# Add mDNSResponder (default: yes)
	if [ "$ADD_LAUNCHD_MDNSRESPONDER" = "n" ]; then 
		# Disable mDNSResponder
		rm -f ${MOUNT}/System/Library/LaunchDaemons/com.apple.mDNSResponder.plist
		rm -f ${MOUNT}/System/Library/LaunchDaemons/com.apple.mDNSResponderHelper.plist
	fi

	# Add portmap (default: yes)
	if [ "$ADD_LAUNCHD_PORTMAP" = "n" ]; then 
		# Disable portmap
		rm -f ${MOUNT}/System/Library/LaunchDaemons/com.apple.portmap.plist
	fi
	# Add statd (default: yes)
	if [ "$ADD_LAUNCHD_STATD" = "n" ]; then 
		# Disable statd
		rm -f ${MOUNT}/System/Library/LaunchDaemons/com.apple.statd.notify.plist
	fi

	# Add a synthetic custom "shell" launched by launchd (default: no)
	if [ "$ADD_LAUNCHD_NANOSHELL" = "y" ]; then 
		# A launchd plist (org.puredarwin.nanoshell.plist) run a synthetic custom "shell" (pd_nanoshell)
		chmod 644 ${MOUNT}/System/Library/LaunchDaemons/org.puredarwin.nanoshell.plist
		chmod +x ${MOUNT}/usr/local/share/puredarwin/scripts/pd_nanoshell
	else	
		# Disable launchd plist to run a synthetic custom "shell" (pd_nanoshell)
		rm -f ${MOUNT}/System/Library/LaunchDaemons/org.puredarwin.nanoshell.plist
	fi

	# Add a tiny installer script launched by launchd (default: no)
	if [ "$ADD_LAUNCHD_INSTALLER" = "y" ]; then 
		# A launchd plist (org.puredarwin.installer.plist) run a CLI installer (pd_installer)
		chmod 644 ${MOUNT}/System/Library/LaunchDaemons/org.puredarwin.installer.plist
		chmod +x ${MOUNT}/usr/local/share/puredarwin/scripts/pd_installer

		# not needed in this scenario..
		rm -f \
		${MOUNT}/System/Library/LaunchDaemons/com.apple.SystemStarter.plist \
		${MOUNT}/System/Library/LaunchDaemons/com.apple.atrun.plist  \
		${MOUNT}/System/Library/LaunchDaemons/com.apple.bootlog.plist \
		${MOUNT}/System/Library/LaunchDaemons/com.apple.bsd.dirhelper.plist \
		${MOUNT}/System/Library/LaunchDaemons/com.apple.diskarbitrationd.plist \
		${MOUNT}/System/Library/LaunchDaemons/com.apple.dyld.plist \
		${MOUNT}/System/Library/LaunchDaemons/com.apple.dynamic_pager.plist \
		${MOUNT}/System/Library/LaunchDaemons/com.apple.firmwaresyncd.plist \
		${MOUNT}/System/Library/LaunchDaemons/com.apple.hidd.plist\
		${MOUNT}/System/Library/LaunchDaemons/com.apple.kextd.plist \
		${MOUNT}/System/Library/LaunchDaemons/com.apple.update.plist\
		${MOUNT}/System/Library/LaunchDaemons/finger.plist \
		${MOUNT}/System/Library/LaunchDaemons/org.puredarwin.ddistnoted.plist
	else	
		# Disable launchd plist to run a synthetic custom "shell" (pd_installer)
		rm -f ${MOUNT}/System/Library/LaunchDaemons/org.puredarwin.installer.plist
	fi
fi

# (default: no)
if [ "$ADD_RELEASE_NANO" = "y" ]; then 
	#FIXME: below seems needed for network support!
	rm -f ${MOUNT}/System/Library/LaunchDaemons/com.apple.DirectoryServices.plist
	rm -f ${MOUNT}/System/Library/LaunchDaemons/com.apple.DirectoryServicesLocal.plist
	rm -f ${MOUNT}/System/Library/LaunchDaemons/com.apple.DirectoryServicesInstallDaemon.plist
fi


###############################################################################
# REDUCING TARGET DISK SIZE
###############################################################################


# Keep developer stuff (default: y)
if [ "$ADD_DEVELOPER" = "n" ]; then
	echo "Cleaning up unneeded developer files from ${MOUNT}..."
	rm -rf ${MOUNT}/Developer      # saves little   (fixme, only if "Developer" has not been selected)
	rm -rf ${MOUNT}/usr/include/   # saves > 150 MB (fixme, only if "Developer" has not been selected)
#	find ${MOUNT}/ -type f | grep "\.h$" | xargs -I {} rm -f {} # more header files (fixme, only if "Developer" has not been selected)
	rm -rf ${MOUNT}/AppleInternal/ # (fixme, only if "Developer" has not been selected)
	#rm -rf ${MOUNT}/usr/lib/libSystem.B_debug.dylib   # saves ~14M
	#rm -rf ${MOUNT}/usr/lib/libSystem.B_profile.dylib # saves ~11M
	find ${MOUNT} -name '.svn' | xargs rm -R
#else

	# Macports sources
	# http://guide.macports.org/#installing.macports.subversion
	#
	#svn co http://svn.macports.org/repository/macports/trunk/base

	# Libdispatch sources
	# http://svn.macosforge.org/repository/libdispatch/trunk/INSTALL
	#
	#svn checkout http://svn.macosforge.org/repository/libdispatch/trunk
fi

###############################################################################
# PERMISSIONS 
###############################################################################

echo "Fixing permissions"
chown root:wheel ${MOUNT}/sbin
chown root:wheel ${MOUNT}/mach_kernel
chown -R root:wheel ${MOUNT}/System/Library/Extensions/
chmod -R 0644 $MOUNT/System/Library/Extensions/
chown -R root:wheel $MOUNT/var/empty # for sshd

# ZFS is disabled since MacOSForge also dropped it.
#
# zfs perms according to http://zfs.macosforge.org/trac/wiki/downloads
#chown -R root:wheel /System/Library/Extensions/zfs.kext
#chown -R root:wheel /System/Library/Filesystems/zfs.fs
#chown -R root:wheel /usr/sbin/zpool
#chown -R root:wheel /usr/sbin/zfs
#chown -R root:wheel /usr/lib/libzfs.dylib

###############################################################################
# CACHE AND EXTENTIONS.MKEXT 
###############################################################################

echo "Set Extensions.mkext invocation"
touch $MOUNT/System/Library/Extensions

# Add creation of kext cache file (default: y)
if [ ! "$ADD_KEXTCACHE" = "n" ]; then
	mkdir -p $MOUNT/System/Library/Caches/com.apple.kernelcaches
	kextcache -a $ARCH -s -l -n -c "$MOUNT/System/Library/Caches/com.apple.kernelcaches/kernelcache.DEADBEEF" -k -K "$MOUNT/mach_kernel" -m "$MOUNT/System/Library/Extensions.mkext" "$MOUNT/System/Library/Extensions"
	# ...leads to:
	#	Can't resolve dependencies amongst kexts for prelinked kernel.
	#	Failed to generate prelinked kernel.

fi

# Force completion of pending disk writes
/bin/sync

###############################################################################
# ISO / VMWAREVM / VMDK / DMG / etc..
###############################################################################

# Detect image extension (iso|vmwarevm|vmdk|dmg|*) and act in consequences 
if [ ! $EXT = "" ]; then

	# Some .vmx variables
	if [ "$DARWIN_RELEASE" = "10" ]; then
		T_GUESTOS="darwin10";	# Darwin 10
	else
		T_GUESTOS="darwin"	# Darwin 9 and prior
	fi	
	
	T_TARGET_EXT=$(basename $TARGET | awk -F '.' '{print $NF}')
	case $T_TARGET_EXT in

		###############################################################
		# ISO 9660 CD-ROM filesystem (.iso)
		###############################################################
		iso)
		T_TARGET=$(dirname $TARGET)/$(basename $TARGET | awk -F '.' '{print $1".iso"}')
		;;
		
		###############################################################
		# VMware virtual disk (.vmdk) 
		###############################################################
		vmdk)
		T_TARGET=$(dirname $TARGET)/$(basename $TARGET | awk -F '.' '{print $1".iso"}')
		# Forced converting iso to VMware vmdk
		echo "Converting image to VMware VMDK disk image, please wait..."
		$QEMUIMG_BIN convert -O vmdk $T_TARGET $(dirname $TARGET)/$(basename $TARGET | awk -F '.' '{print $1".vmdk"}')
		;;
		
		###############################################################
		# VMware virtual machine package (.vmwarevm)
		###############################################################
		vmwarevm)
		T_TARGET="$(basename $TARGET | awk -F '.' '{print $1".iso"}')"
		# Moving the .vmwarevm file to .iso
		mv "$TARGET" "$T_TARGET"
		# Creating the .vmwarevm directory
		mkdir -p "$TARGET"
		# Moving the .iso file to the .vmwarevm directory
		mv "$T_TARGET" "$TARGET/$T_TARGET" 
		
		cat > $TARGET/$(basename $TARGET | awk -F '.' '{print $1".vmx"}') <<EOOF
.encoding = "UTF-8"
bios.bootDelay = "5000"
config.version = "8"
displayName = "`/bin/date +"%y%m%d%H%M "`${DARWIN_RELEASE} / ${ARCH} / $PUREDARWIN_RELEASE"
ehci.present = "TRUE"
ethernet0.linkStatePropagation.enable = "FALSE"
ethernet0.present = "TRUE"
ethernet0.virtualDev = "e1000"
ethernet0.wakeOnPcktRcv = "FALSE"
floppy0.present = "FALSE"
ft.secondary0.enabled = "TRUE"
guestOS = "$T_GUESTOS"
ich7m.present = "TRUE"
ide0:0.deviceType = "cdrom-image"
ide0:0.fileName = "`basename $T_TARGET`"
ide0:0.present = "TRUE"
keyboardAndMouseProfile = "macProfile"
memsize = "128"
nvram = "$VOLNAME.nvram"
pciBridge0.present = "TRUE"
pciBridge4.functions = "8"
pciBridge4.present = "TRUE"
pciBridge4.virtualDev = "pcieRootPort"
pciBridge5.functions = "8"
pciBridge5.present = "TRUE"
pciBridge5.virtualDev = "pcieRootPort"
pciBridge6.functions = "8"
pciBridge6.present = "TRUE"
pciBridge6.virtualDev = "pcieRootPort"
pciBridge7.functions = "8"
pciBridge7.present = "TRUE"
pciBridge7.virtualDev = "pcieRootPort"
powerType.powerOff = "soft"
powerType.powerOn = "soft"
powerType.reset = "soft"
powerType.suspend = "soft"
printers.enabled = "FALSE"
roamingVM.exitBehavior = "go"
scsi0.present = "TRUE"
scsi0.virtualDev = "lsilogic"
scsi0:0.fileName = ""
scsi0:0.present = "FALSE"
serial0.fileType = "thinprint"
serial0.present = "FALSE"
smc.present = "TRUE"
tools.syncTime = "TRUE"
tools.upgrade.policy = "upgradeAtPowerCycle"
usb.present = "TRUE"
virtualHW.productCompatibility = "hosted"
virtualHW.version = "7"
vmci0.present = "TRUE"
EOOF

		#Convert to VMware VMDK disk image for read-write support? (default: y)
		if [ ! "$ADD_VMWARE_VMDK" = "n" ]; then
			# Converting iso to VMware vmdk
			echo "Converting image to VMware VMDK disk image, please wait..."
			$QEMUIMG_BIN convert -O vmdk $TARGET/$T_TARGET $TARGET/$(basename $TARGET | awk -F '.' '{print $1".vmdk"}')
			
			cat > $TARGET/$(basename $TARGET | awk -F '.' '{print $1".vmx"}') <<EOOF
.encoding = "UTF-8"
bios.bootDelay = "5000"
config.version = "8"
displayName = "`/bin/date +"%y%m%d%H%M "`${DARWIN_RELEASE} / ${ARCH} / $PUREDARWIN_RELEASE"
ehci.present = "TRUE"
ethernet0.linkStatePropagation.enable = "FALSE"
ethernet0.present = "TRUE"
ethernet0.virtualDev = "e1000"
ethernet0.wakeOnPcktRcv = "FALSE"
floppy0.present = "FALSE"
ft.secondary0.enabled = "TRUE"
guestOS = "$T_GUESTOS"
ich7m.present = "TRUE"
ide0:0.fileName = "$(basename $T_TARGET | awk -F '.' '{print $1".vmdk"}')"
ide0:0.present = "TRUE"
ide0:0.redo = ""
ide1:0.autodetect = "TRUE"
ide1:0.deviceType = "cdrom-image"
ide1:0.fileName = "`basename $T_TARGET`"
ide1:0.present = "TRUE"
keyboardAndMouseProfile = "macProfile"
memsize = "128"
nvram = "$VOLNAME.nvram"
pciBridge0.present = "TRUE"
pciBridge4.functions = "8"
pciBridge4.present = "TRUE"
pciBridge4.virtualDev = "pcieRootPort"
pciBridge5.functions = "8"
pciBridge5.present = "TRUE"
pciBridge5.virtualDev = "pcieRootPort"
pciBridge6.functions = "8"
pciBridge6.present = "TRUE"
pciBridge6.virtualDev = "pcieRootPort"
pciBridge7.functions = "8"
pciBridge7.present = "TRUE"
pciBridge7.virtualDev = "pcieRootPort"
powerType.powerOff = "soft"
powerType.powerOn = "soft"
powerType.reset = "soft"
powerType.suspend = "soft"
printers.enabled = "FALSE"
roamingVM.exitBehavior = "go"
scsi0.present = "TRUE"
scsi0.virtualDev = "lsilogic"
scsi0:0.fileName = ""
scsi0:0.present = "FALSE"
serial0.fileType = "thinprint"
serial0.present = "FALSE"
smc.present = "TRUE"
tools.syncTime = "TRUE"
tools.upgrade.policy = "upgradeAtPowerCycle"
usb.generic.autoconnect = "FALSE"
usb.present = "TRUE"
virtualHW.productCompatibility = "hosted"
virtualHW.version = "7"
vmci0.present = "TRUE"
EOOF
		fi
		


		# Add an (additional) IDE disk device to the .vmwarevm? (default: n)
		if [ "$ADD_VMWARE_IDE_DRIVE" = "y" ]; then
			# Creating a (second) VMware4 disk image via qemu-img
			# SIZE at least equal to "the parent" one (most of the time, the bootstrap one)
			# FIXME add check on the size
			qemu-img create -f vmdk $TARGET/second.vmdk 2048M

			# Reflect the disk image in the .vmx file
			cat >> $TARGET/$(basename $TARGET | awk -F '.' '{print $1".vmx"}') <<EOOF
ide0:1.present = "TRUE"
ide0:1.fileName = "second.vmdk"
ide0:1.redo = ""
EOOF
		fi

		;;
		
		###############################################################
		# VAX COFF executable (.dmg)
		###############################################################
		dmg)
		;;
		
		###############################################################
		# Default (.*)
		###############################################################
		*) 
		;;
	esac

	# FIXME too permissive 
	# 	Since the installation is done at root over a normal user, 
	# 	in finder the image is open in read-only after clickclick.. owner/perms
	# 	need to be changed for rw (or the image needs to be mount as root)
	chmod -R 777 $TARGET
	chown -R 501:staff $TARGET

	echo "Installation on ${TARGET} complete."
else
	# Force completion of pending disk writes
	/bin/sync
	
	# Umounting the volume
	echo "Unmounting..."
	umount -f ${MOUNT}

	echo "Installation on ${TARGET} complete. "
fi
